<template>
  <el-dialog
    :title="isEdit ? '编辑职员' : '添加职员'"
    :visible="dialogVisible"
    width="500px"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="100px"
      size="small"
    >
      <el-form-item label="照片">
        <Upload ref="upload" :thumb="form.photo" @handleAvatarSuccess="handleAvatarSuccess"></Upload>
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      
      <el-form-item label="管辖范围" prop="building">
        <el-cascader
          size="small"
          v-model="buildingValue"
          :options="buildingOptions"
          @change="handleBuildingChange"
          :props="{ value: 'id', label: 'name', multiple: true }"
          clearable
          style="width: 100%"
        >
        </el-cascader>
      </el-form-item>
      
      <el-form-item label="职员类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择职员类型" style="width: 100%">
          <el-option
            v-for="item in staffTypeList"
            :key="item.id"  
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="身份证号" prop="cardid">
        <el-input v-model="form.cardid" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      
      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入联系电话"></el-input>
      </el-form-item>
    </el-form>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel" size="small">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" size="small">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add } from '@/api/staffs'
import Upload from './Upload.vue'
import { list as getBuildings } from '@/api/building'
import { lists as getStaffTypes } from '@/api/staffs'

export default {
  name: 'DialogStaff',
  components: {
    Upload
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      buildingValue: [],
      buildingOptions: [],
      form: {
        id: 0,
        name: '',
        photo: '',
        type: '',
        sex: 1,
        mobile: '',
        cardid: '',
        building: []
      },
      buildingList: [],
      staffTypeList: [],
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        type: [{ required: true, message: '请选择职员类型', trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        cardid: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        building: [{ required: true, type: 'array', message: '请选择管辖范围', trigger: 'change' }]
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.getBuildingList()
        this.getStaffTypeList()
        
        if (this.isEdit && this.editData) {
          this.form = {
            id: this.editData.id || 0,
            name: this.editData.name || '',
            photo: this.editData.photo || '',
            type: this.editData.type || '',
            sex: this.editData.sex !== undefined ? this.editData.sex : 1,
            mobile: this.editData.mobile || '',
            cardid: this.editData.cardid || '',
            building: []
          }

          console.log('编辑数据中的building字段:', this.editData.building);
          if (this.editData.building) {
            if (Array.isArray(this.editData.building) && this.editData.building.length > 0) {
              if (typeof this.editData.building[0] === 'object' && this.editData.building[0] !== null) {
                this.buildingValue = this.editData.building.map(item => {
                  return item.buildingid || item.id || item.value;
                }).filter(id => id !== undefined);

                this.form.building = [...this.buildingValue];
              } else {
                this.buildingValue = [...this.editData.building];
                this.form.building = [...this.editData.building];
              }
              console.log('处理后的buildingValue:', this.buildingValue);
              console.log('处理后的form.building:', this.form.building);
            } else {
              this.buildingValue = [];
              this.form.building = [];
              console.log('building字段为空数组');
            }
          } else {
            this.buildingValue = [];
            this.form.building = [];
            console.log('building字段为空');
          }
        } else {
          this.resetForm()
        }
      }
    }
  },
  methods: {
    async getBuildingList() {
      try {
        const res = await getBuildings({ page: 1, psize: 1000 })
        this.buildingOptions = res.data.list || []
      } catch (error) {
        console.error('获取建筑列表失败:', error)
        this.$message.error('获取建筑列表失败!')
      }
    },
    
    async getStaffTypeList() {
      try {
        const res = await getStaffTypes({ page: 1, psize: 1000 })
        this.staffTypeList = res.data.list || []
      } catch (error) {
        console.error('获取职员类型列表失败:', error)
        this.$message.error('获取职员类型列表失败!')
      }
    },
    
    handleBuildingChange(buildingIds) {
      this.buildingValue = buildingIds;
      console.log('管辖范围选择变化:', buildingIds);

      this.form.building = buildingIds || [];
      console.log('form.building更新为:', this.form.building);

      this.$refs.form?.validateField('building');
    },
    
    handleAvatarSuccess(imageInfo) {
      this.form.photo = imageInfo.data
    },
    
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            console.log('表单验证通过');
            let buildingParams = [];
            console.log('提交前form.building的值:', this.form.building);
            console.log('提交前buildingValue的值:', this.buildingValue);

            if (this.form.building && Array.isArray(this.form.building) && this.form.building.length > 0) {
              let buildingIds = this.form.building;
              if (Array.isArray(this.form.building[0])) {
                buildingIds = this.form.building.map(arr => 
                  arr.length > 0 ? arr[arr.length - 1] : null
                ).filter(id => id !== null);
              }

              if (buildingIds.length > 0) {
                if (typeof buildingIds[0] !== 'object') {
                  buildingParams = buildingIds.map(id => {
                    const numId = Number(id);
                    return isNaN(numId) ? null : { buildingid: numId };
                  }).filter(item => item !== null);
                } else if (buildingIds[0].buildingid) {
                  buildingParams = buildingIds.filter(item => item && item.buildingid);
                }
              }
            }

            if (!Array.isArray(buildingParams)) {
              buildingParams = [];
            }
            
            const params = {
              id: this.form.id || 0,
              name: this.form.name,
              photo: this.form.photo || '',
              type: Number(this.form.type),
              sex: Number(this.form.sex),
              mobile: this.form.mobile,
              cardid: this.form.cardid,
              building: buildingParams
            }
            
            console.log('提交的参数:', params);

            await add(params)
            this.$message.success(`${this.isEdit ? '编辑' : '添加'}成功!`)
            this.$emit('refreshList')
            this.handleCancel()
          } catch (error) {
            console.error('保存失败:', error)
            if (error && error.message) {
              this.$message.error(`${this.isEdit ? '编辑' : '添加'}失败: ${error.message}`)
            } else {
              this.$message.error(`${this.isEdit ? '编辑' : '添加'}失败!`)
            }
          }
        } else {
          console.log('表单验证失败');
        }
      })
    },
    
    handleCancel() {
      this.$emit('handleCancel')
    },
    
    handleClose() {
      this.$emit('handleCancel')
    },
    
    resetForm() {
      this.$refs.form && this.$refs.form.resetFields()
      this.form = {
        id: 0,
        name: '',
        photo: '',
        type: '',
        sex: 1,
        mobile: '',
        cardid: '',
        building: []
      }
      this.buildingValue = []
      if (this.$refs.upload) {
        this.$refs.upload.imageUrl = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>